/*
 * Copyright (c) China Telecom Cloud Technology Co., Ltd. 2024-2025. All rights reserved.
 */
#ifndef DYNAMO_PUBLISHER_H
#define DYNAMO_PUBLISHER_H

#include "KVCachePublisher.h"
#include "MemoryPool.h"
#include "dynamo_adapter.h"
#include <cstdlib>
#include <thread>
#include <vector>

// 单次nats消息最大携带的hashId数量，防止超过nats协议最大报文长度
#define MAX_HASHIDS_PER_NATS_REQ    (1024) 



class DynamoPublisher final : public KVCachePublisher {
public:
    DynamoPublisher();

    
    ~DynamoPublisher() {
        free_nats_connection();
        unreg();
    };


    /**
     *! @brief 其实一个线程每个1s向发布当前KV Cache的变化状况(哪些被删除了，新增了哪些)
     * 
     * @param pool 
     */
    void reg(MemoryPool *pool) noexcept override;

    /* 注销KVCachePublisher */

    /**
     * @brief 等待发布线程执行完成
     * 
     */
    void unreg() noexcept override;

private:
    // 缓存的hashId列表，2个槽位，采用ping-pong机制
    std::vector<BlockHashId> _cachedHashIds[2]; 

    // 指示哪个槽位是最新的缓存信息
    int8_t _pos : 1; 
    int8_t _reserved : 7;

    uint64_t _eventIdCnt; // eventId计数器，每次上报+1

    // 后台独立线程，周期性从MemoryPool中查询缓存信息并上报给dynamo
    std::thread _thread; 

    /**
     *! @brief 
     * 
     * @param parentHashId 
     * @param blkInfo 
     * @param blkInfoNum 
     */
    void publishOneStoredEvent(int64_t parentHashId,
                            StoredBlockData *blkInfo,
                            int32_t &blkInfoNum
                        );
    

    /**
     *! @brief 
     * 
     * @param addedHashIds 
     */
    void publishStoredEventBatch(std::vector<BlockHashId> &addedHashIds);



    /**
     *! @brief 
     * 
     * @param removedHashIds 
     */
    void publishRemovedEventBatch(std::vector<uint64_t> &removedHashIds);
};

#endif // DYNAMO_PUBLISHER_H